package com.hsgene.user.service.impl;

import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.common.util.validation.FieldChecker;
import com.hsgene.order.constants.v1.SexType;
import com.hsgene.user.condition.ShoppingMallCustomerCondition;
import com.hsgene.user.domain.User;
import com.hsgene.user.dto.user.customer.CustomerDto;
import com.hsgene.user.dto.user.customer.ShoppingMallCustomerDto;
import com.hsgene.user.exception.UserErrorCode;
import com.hsgene.user.persistence.CustomerRepository;
import com.hsgene.user.persistence.UserRepository;
import com.hsgene.user.service.CustomerService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 客户信息ServiceImpl
 *
 * @author wangbing
 * @version 1.0, 2018/7/9
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private CustomerRepository customerRepository;

    @Resource
    private UserRepository userRepository;

    @Override
    public ApiResult<CustomerDto> findCustomerById(String userId) {
        FieldChecker.checkEmpty(userId, "userId");

        CustomerDto customer = customerRepository.findCustomerById(userId);
        if (customer == null) {
            return ApiResult.fail(UserErrorCode.USER_NOT_EXISTED);
        }

        return ApiResult.succ(customer);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public ApiResult<NullObject> updateCustomer(CustomerDto customer) {
        CustomerDto existed = customerRepository.findCustomerById(customer.getUserId());
        if (existed == null) {
            return ApiResult.fail(UserErrorCode.USER_NOT_EXISTED);
        }
        User user = userRepository.findById(customer.getUserId());
        Date current = new Date();
        LocalDate now1 = LocalDate.now();
        LocalDate now2 = now1.plusYears(2);
        now2.until(now1, ChronoUnit.YEARS);
        user.setNickName(customer.getNickName());
        user.setHeadImage(customer.getHeadImage());
        user.setGender(customer.getGender());
        user.setProfession(customer.getProfession());
        user.setBirthday(customer.getBirthday());
        if (customer.getBirthday() != null) {
            LocalDate birthday = customer.getBirthday().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate now = current.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            short age = (short) birthday.until(now, ChronoUnit.YEARS);
            user.setAge(age < 0 ? 0 : age);
        }
        user.setUpdateTime(current);
        userRepository.updateUser(user);

        return ApiResult.succ();
    }

    /**
     * 用户管理列表
     * @param condition 查询条件
     * @return
     */
    @Override
    public ApiResult customers(ShoppingMallCustomerCondition condition) {
        FieldChecker.checkEmpty(condition.getLimitHelper(),"分页条件");
        int count = customerRepository.count(condition);
        Pagination<ShoppingMallCustomerDto> pagination = Pagination.newInstance(condition.getLimitHelper(), count);
        List<ShoppingMallCustomerDto> customerDtos = new ArrayList<>();
        if(count>0){
            customerDtos = customerRepository.customers(condition);
            if(customerDtos!=null&&customerDtos.size()>0){
                int rowNum = (condition.getLimitHelper().getPage()-1)*condition.getLimitHelper().getSize();
                for(int i = 0;i<customerDtos.size();i++){
                    ShoppingMallCustomerDto customerDto = customerDtos.get(i);
                    //如果用户头像为空则使用默认头像
                    customerDto.setAvatar(StringUtils.isEmpty(customerDto.getAvatar())?customerDto.getDefaultAvatar():customerDto.getAvatar());
                    if(customerDto.getGender()!=null){
                        if(customerDto.getGender()==1){
                            customerDto.setGenderDesc("女");
                        }else {
                            customerDto.setGenderDesc("男");
                        }
                    }
                    customerDto.setNumber(rowNum+1+i);
                }
            }
        }
        pagination.setResult(customerDtos);
        return new ApiResult(200,"success","数据获取成功",pagination);
    }
}
